<template>
    <van-nav-bar :title="isRegistered ? '注册' : '登录'" left-arrow @click-left="router.replace('/home')" fixed />
    <div class="occupy">
        <!-- 占位盒子，导航栏fixed脱标盖住商品列表 -->
    </div>
    <div class="profile">
        <van-image fit="cover" width="2.3467rem" height="2.3467rem" position="cebter" round :src="getUserInfo.avatar" />
    </div>

    <van-form @submit="onSubmit">
        <van-cell-group inset>
            <van-field v-model.trim="getUserInfo.name" name="name" label="用户名" placeholder="用户名" :rules="[
                { required: true, message: '请填写用户名' },
                {
                    pattern: /^[-_a-zA-Z0-9]{4,16}$/,
                    message: '只能包含4-16位字母数字下划线减号',
                },]" />
            <van-field v-model="getUserInfo.password" type="password" name="password" label="密码" placeholder="密码" :rules="[
                { required: true, message: '请填写密码' },
                {
                    pattern: /^[-_a-zA-Z0-9]{6,16}$/,
                    message: '只能包含6-16位字母数字下划线减号',
                },

            ]" />
            <van-field v-if="isRegistered" v-model.lazy.trim="getUserInfo.avatar" type="url" name="avatar" label="头像"
                placeholder="图片地址" :rules="[
                    { required: true, message: '请填写图片地址' },
                    {
                        pattern:
                            /^(http|ftp|https):\/\/([\w\-]+(\.[\w\-]+)*\/)*[\w\-]+(\.[\w\-]+)*\/?(\?([\w\-\.,@?^=%&:\/~\+#]*)+)?/,
                        message: '请输入有效的网址',
                    },
                ]" />
            <van-field v-if="isRegistered" name="radio" label="单选框">
                <template #input>
                    <van-radio-group v-model="getUserInfo.sex" direction="horizontal">
                        <van-radio name="1">男</van-radio>
                        <van-radio name="2">女</van-radio>
                    </van-radio-group>
                </template>
            </van-field>
            <van-field v-if="isRegistered" v-model.lazy.trim="getUserInfo.sign" type="text" name="sign" label="签名"
                placeholder="个性签名" :rules="[{ required: true, message: '请填写个性签名' }]" />
            <van-field v-if="isRegistered" v-model.lazy.trim="getUserInfo.secret_answer" type="text" name="secret_answer"
                label="密保" placeholder="验证密保" :rules="[{ required: true, message: '请填写密保' }]" />
        </van-cell-group>
        <div style="margin: 16px;">
            <van-button round block :type="isRegistered == true ? 'primary' : 'success'" native-type="submit"
                style="margin-bottom: 0.3rem;">
                {{ isRegistered == true ? '注册' : '登录' }}
            </van-button>
            <van-button v-if="!isRegistered" round block type="primary" @click="signUp" style="margin-bottom: 0.3rem;">
                注册
            </van-button>
            <van-button v-if="isRegistered" plain round block type="primary" @click="backLogin">
                返回登录
            </van-button>
        </div>
    </van-form>
</template>

<script setup>
import { reactive, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import getAvatar from '@/utils/avatar.js'
import { login, register } from '@/api/auth.js'
import { showSuccessToast, showFailToast } from 'vant';

import { setToken } from '@/utils/token.js'
import { resetLogin, setData, getData } from '@/utils/userCache.js'
import { useUserStore } from '@/stores/user.js'
import { useCartStore } from '@/stores/cart.js'
const userStore = useUserStore();
const userCart = useCartStore();


const router = useRouter();

let isRegistered = ref(false)


let getUserInfo = reactive({
    avatar: getAvatar(),
    name: '',
    password: '',
    sex: '1',
    sign: '',
    secret_answer: ''
})

const onSubmit = async (values) => {
    if (isRegistered.value == false) {
        let res = await login(values)
        if (res.code == 1) {
            showSuccessToast({
                message: '登录成功'
            });
            //将用户账号密码持久化，获取用户信息接口要用
            localStorage.setItem('info', btoa(encodeURI(JSON.stringify({
                name: getUserInfo.name,
                pwd: getUserInfo.password,
            }))))
            // token设置
            setToken(res.data.token, res.data.expires_in);
            // 重置上次登录用户
            resetLogin();
            // 本地用户数据设置
            setData(getUserInfo.name, {
                avatar: res.data.avatar,
                pwd: getUserInfo.password,
                sign: res.data.sign,
                sex: res.data.sex,
                lastLogin: true,
            });
            //登录成功后请求服务器拿到购物车数据放到仓库里，以后每次刷新页面再app组件生命周期函数中判断登录状态，重新拿购物车数据
            userCart.getCart()
            router.replace('/home')
        } else {
            showFailToast({
                message: '账号或者密码不正确'
            });
        }
    } else {
        let res = await register(getUserInfo)
        if (res.code == 1) {
            showSuccessToast({
                message: '注册成功'
            });
            getUserInfo.avatar = values.avatar
            getUserInfo.name = values.name
            getUserInfo.password = ''
            getUserInfo.sex = '1'
            getUserInfo.sign = ''
            getUserInfo.secret_answer = ''
            isRegistered.value = false
        } else {
            showFailToast({
                message: '注册失败'
            });
        }

    }
};

let signUp = () => {
    isRegistered.value = true
    getUserInfo.name = ''
    getUserInfo.password = ''
}
let backLogin = () => {
    isRegistered.value = false
    getUserInfo.name = ''
    getUserInfo.password = ''
}

watch(() => getUserInfo.name, (val) => {
    const avatar = getData(val).avatar;
    if (avatar) {
        getUserInfo.avatar = avatar;
    }
}, { deep: true }) 
</script>

<style  lang="scss" scoped>
.profile {
    padding: 1.5467rem;
    text-align: center;
}

.occupy {
    height: 1.2267rem;
}
</style>